package com.jzg.mvc.api.cabinet;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.core.Path;
import com.jfinal.ext.kit.DateKit;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jzg.common.controller.BaseController;
import com.jzg.common.entity.Box;
import com.jzg.common.entity.Module;
import com.jzg.common.model.biz.Cab;
import com.jzg.common.model.biz.CabCard;
import com.jzg.common.model.biz.CabModule;
import com.jzg.common.model.biz.CabModuleBoard;
import com.jzg.common.model.biz.CabModuleFaultBox;
import com.jzg.common.model.biz.CabStore;
import com.jzg.common.model.biz.CabStoreBox;
import com.jzg.common.model.biz.CabStoreBoxLog;
import com.jzg.common.model.biz.CabStoreLog;
import com.jzg.common.model.biz.CabStoreUser;
import com.jzg.common.model.biz.CabUser;
import com.jzg.common.model.sys.SysOrg;
import com.jzg.common.render.RenderLayuiBean;
import com.jzg.common.render.Store;
import com.jzg.common.util.CaseUtil;
import com.jzg.common.util.UuidUtil;
import com.jzg.mvc.api.cabinet.service.CabService;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Path(value = "/api/cab/store", viewPath = "")
public class StoreController extends BaseController {
	@Inject
	private CabService srv;
	
	private static Prop propConfig = PropKit.use("app-config-dev.txt");

	/**
	 * 在柜案件列表
	 */
	public void listData() {
		int pageNumber = getParaToInt("page", 1);
		int pageSize = getParaToInt("limit", 10);
		String keyword = getPara("keyword");
		String caseNo = getPara("caseNo");
		String userId = getPara("userId");
		String cabId = getPara("cabId");
		String sqlExceptSelect = " FROM " + CabStore.TABLE_NAME + " O  WHERE 1=1 ";
		if (!StrKit.isBlank(keyword)) {
			sqlExceptSelect += " AND ( O.USERNAME LIKE '%" + keyword + "%' ) ";
		}
		if (!StrKit.isBlank(caseNo)) {
			sqlExceptSelect += " AND O.ID='" + caseNo + "' ";
		}
		if (!StrKit.isBlank(cabId)) {
			sqlExceptSelect += " AND O.CABID='" + cabId + "' ";
		}
		if (!StrKit.isBlank(userId)) {
			CabUser cabUser = CabUser.dao
					.findFirst("select * from " + CabUser.TABLE_NAME + " where cabId=? and userId=? ", cabId, userId);
			if (cabUser != null) {
				if (!cabUser.getRoleKey().contains("all")) {
					sqlExceptSelect += " AND O.ID IN (SELECT STOREID FROM " + CabStoreUser.TABLE_NAME + " WHERE USERID="
							+ userId + " )";
				}
			}
		}
		sqlExceptSelect += "  ORDER BY O.FIELD5 ASC ";
		String sqlSelect = " '' legalName,";
		if(StrKit.equals("PL-JZG-53010305-2224", cabId)) {
			sqlSelect = "O.field4 legalName,";
		}
		Page<CabStore> page = CabStore.dao.paginate(pageNumber, pageSize, "select O.*, "+sqlSelect
				+ " (select `NAME` from sys_user where ID = (select userId from biz_cab_store_user where  cabId=O.cabId and storeId = O.id and src='1' LIMIT 1) ) userName, "
				+ " (select createTime from biz_cab_store_log where cabId=O.cabId and storeId=O.id ORDER BY createTime DESC LIMIT 1) addTime ",
				sqlExceptSelect);
		RenderLayuiBean renderBean=new RenderLayuiBean();
		renderBean.setCode(0);
		renderBean.setMsg("查询成功");
		renderBean.setData(page.getList());
		renderBean.setCount(page.getTotalRow());
		if(!propConfig.getBoolean("devMode")) {
			Record user = Db.use("plga").findFirst("select * from Manage WHERE NId = ?",userId);
			if(user!=null) {
				Record manaRole = Db.use("plga").findFirst("select * from ManaRole WHERE NId = ?",user.getInt("NGroup"));
				if(manaRole!=null) {
					if(manaRole.getStr("SPermissions").contains(propConfig.get("caseAuthCode"))) {
						renderBean.setAuth("1");
					}
				}
			}
		}
		this.renderJson(renderBean);
	}

	public void getById() {
		String caseNo = getPara("caseNo");
		// String cabId = getPara("cabId");
		CabStore cabStore = CabStore.dao.findFirst("select t.*, "
				+ " (select `NAME` from sys_user where id=(select userId from biz_cab_store_user where  cabId=t.cabId and storeId = t.id and src='1' LIMIT 1) ) userName from "
				+ CabStore.TABLE_NAME + " t where t.id=?", caseNo);
		renderSuccess("查询成功！", cabStore);
	}

	/**
	 * 案件存取日志列表
	 */
	public void logListData() {
		int pageNumber = getParaToInt("page", 1);
		int pageSize = getParaToInt("limit", 10);
		String keyword = getPara("keyword");
		String startTime = getPara("startTime");
		String endTime = getPara("endTime");
		String caseNo = getPara("caseNo");
		// String userId = getPara("userId");

		String sqlExceptSelect = " FROM " + CabStoreLog.TABLE_NAME + " O," + Cab.TABLE_NAME + " b," + SysOrg.TABLE_NAME
				+ " R  WHERE  O.CABID=B.ID AND B.ORGID=R.ID ";
		if (!StrKit.isBlank(keyword)) {
			sqlExceptSelect += " AND ( O.STOREID = '" + keyword + "' OR  R.NAME LIKE '%" + keyword + "%') ";
		}
		if (!StrKit.isBlank(startTime)) {
			sqlExceptSelect += " AND DATE_FORMAT(O.CREATETIME,'%Y-%m-%d %H:%i:%s') >= STR_TO_DATE('" + startTime
					+ "','%Y-%m-%d %H:%i:%s') ";
		}
		if (!StrKit.isBlank(endTime)) {
			sqlExceptSelect += " AND DATE_FORMAT(O.CREATETIME,'%Y-%m-%d %H:%i:%s') <= STR_TO_DATE('" + endTime
					+ "','%Y-%m-%d %H:%i:%s') ";
		}
		if(!StrKit.isBlank(caseNo)) {
			sqlExceptSelect += " AND O.STOREID='"+caseNo+"' ";
		}//createUserName
		sqlExceptSelect += "  ORDER BY  O.CREATETIME DESC ";
		Page<CabStoreLog> page = CabStoreLog.dao.paginate(pageNumber, pageSize,
				"select o.*,b.orgId,r.`NAME` as orgName,"
						+ " CASE o.`status` WHEN '0' THEN '存入' when '1' then '续存' ELSE '取出' END statusName, "
						+ " ( SELECT NAME FROM SYS_USER WHERE ID=O.CREATEUSERID ) as createUserName ",
				sqlExceptSelect);
		renderLayuiPage(0, page.getList(), "", page.getTotalRow());
	}

	public void boxLogInfo() {
		String cabId = getPara("cabId");
		String logId = getPara("logId");

		if (StrKit.isBlank(cabId)) {
			renderError("参数必填！");
			return;
		}

		CabStoreLog cabStoreLog = CabStoreLog.dao.findById(logId);
		if (cabStoreLog == null) {
			renderError("日志信息不存在，请刷新重试！");
			return;
		}

		List<Module> res = new ArrayList<Module>();

		List<CabModule> cabModules = CabModule.dao
				.find("select * from " + CabModule.TABLE_NAME + " where cabId=? order by type ", cabId);
		for (CabModule cabModule : cabModules) {

			SysOrg sysOrg = SysOrg.dao.findFirst("SELECT * FROM " + SysOrg.TABLE_NAME
					+ " WHERE ID IN (SELECT ORGID FROM " + Cab.TABLE_NAME + " WHERE ID=? ) ", cabId);
			Module module = new Module();
			module.setCabId(cabModule.getCabId());
			module.setCaseNo(cabStoreLog.getId());
			module.setType(cabModule.getType());
			module.setName(sysOrg == null ? cabModule.getName() : sysOrg.getNAME() + "-" + cabModule.getName());
			module.setCode(cabModule.getCode());

			int usedNum = Db.queryInt("select count(*) from " + CabStoreBox.TABLE_NAME + " where moduleId=?",
					cabModule.getId());
			int faultNum = Db.queryInt(
					"select count(*) from " + CabModuleFaultBox.TABLE_NAME + " where status='0' and moduleId=?",
					cabModule.getId());

			module.setUsedNum(usedNum);
			module.setErrorNum(faultNum);
			module.setFreeNum(cabModule.getTotal() - usedNum - faultNum);
			module.setTotal(cabModule.getTotal());

			List<CabModuleBoard> boards = CabModuleBoard.dao.find(
					"select * from " + CabModuleBoard.TABLE_NAME + " where moduleId=? order by serialNo ",
					cabModule.getId());
			cabModule.setBoards(boards);

			List<Box> boxs = new ArrayList<Box>();

			if (boards != null && boards.size() > 0) {
				int boxNo = 0;
				for (int r = 1; r <= 5; r++) {
					for (CabModuleBoard board : boards) {
						for (int i = 0; i < board.getTotal(); i++) {
							boxNo++;
							int xh = boxNo;
							int serialNo = r + i * 5;
							Box box = new Box();
							box.setBoardId(board.getId());
							box.setBoardNo(board.getSerialNo());
							box.setSortNo(xh);
							box.setSerialNo(serialNo);
							box.setBoxStatus("0");
							boxs.add(box);
							if ((i + 1) * 5 >= board.getTotal()) {
								break;
							}
						}
					}
				}
			}

			srv.logBoxStatus(boxs, logId);
			srv.boxActionStatus(boxs, logId);
			module.setBoxs(boxs);
			res.add(module);
		}
		renderSuccess("查询成功！", res);
	}

	/******************************************************
	 * 客户端同步
	 *************************************************/

	/**
	 * 柜子存储授权用户
	 */
	public void getUsers() {
		String cabinetId = getPara("cabinetId");
		String rows = this.getPara("rows");

		try {
			if (!StrKit.isBlank(rows)) {
				JSONArray array = JSONArray.fromObject(rows);
				if (array != null && array.size() > 0) {
//					StringBuffer sb=new StringBuffer();
					for (Object object : array) {
						JSONObject row = JSONObject.fromObject(object);
						if (row != null) {
							CabStoreUser cabStoreUser = CabStoreUser.dao.findById(row.getString("id"));
							if (cabStoreUser == null) {
								cabStoreUser = new CabStoreUser();
								cabStoreUser.setId(row.getString("id"));
								cabStoreUser.setCabId(cabinetId);
								cabStoreUser.setStoreId(row.getString("storeId"));
								cabStoreUser.setUserId(row.getString("userId"));
								cabStoreUser.setSrc(row.getString("src"));
								if (!cabStoreUser.save()) {
									throw new Exception("同步卷宗授权用户失败！");
								}
							}
//							sb.append("'").append(cabStoreUser.getId()).append("'").append(",");
						}
					}
//					if(!StrKit.isBlank(sb.toString())) {
//						Db.delete("delete from "+CabStoreUser.TABLE_NAME+" where cabId=? and  id not in ("+(sb.substring(0,sb.length()-1))+") ",cabinetId);
//					}
				}
			}
			List<CabStoreUser> cabStoreUsers = CabStoreUser.dao
					.find("select * from " + CabStoreUser.TABLE_NAME + " where cabId=? ", cabinetId);
			if (cabStoreUsers != null && cabStoreUsers.size() > 0) {
				this.renderSuccess("同步卷宗授权用户成功!", cabStoreUsers);
				return;
			}
			this.renderError("失败！");
		} catch (Exception e) {
			this.renderError(e.getMessage());
		}
	}

	/**
	 * 柜子显示映射
	 */
	public void getMaps() {
		String cabinetId = getPara("cabinetId");
		List<CabCard> cabCards = CabCard.dao.find("select * from " + CabCard.TABLE_NAME + " where cabId=? ", cabinetId);
		if (cabCards != null && cabCards.size() > 0) {
			this.renderSuccess("成功!", cabCards);
			return;
		}
		this.renderError("失败！");
	}

	/**
	 * 保存以及更新卷宗
	 */
	@Before(Tx.class)
	public void saveStores() {
		String cabinetId = this.getPara("cabinetId");
		String rows = this.getPara("rows");
		if (StrKit.isBlank(rows)) {
			Db.delete("delete from " + CabStore.TABLE_NAME + " where cabId=?", cabinetId);
			Db.delete("delete from " + CabStoreBox.TABLE_NAME + " where cabId=?", cabinetId);
			this.renderError("存储信息空！");
			return;
		}
		try {
			JSONArray array = JSONArray.fromObject(rows);
			if (array != null && array.size() > 0) {
				StringBuffer sb = new StringBuffer();
				List<Store> stores = new LinkedList<Store>();
				for (Object object : array) {
					JSONObject row = JSONObject.fromObject(object);
					if (row != null) {
						CabStore cabStore = CabStore.dao.findFirst(
								"select * from " + CabStore.TABLE_NAME + " where cabId=? and id=? ", cabinetId,
								row.getString("id"));
						if (cabStore == null) {
							cabStore = new CabStore();
							cabStore.setSid(UuidUtil.getUUID());
							cabStore.setId(row.getString("id"));
							cabStore.setCreateTime(DateKit.toDate(row.getString("createTime")));
							cabStore.setUpdateTime(DateKit.toDate(row.getString("updateTime")));
							cabStore.setCabId(cabinetId);
							cabStore.setIsSend("0");
							cabStore.save();
						}
						SysOrg org = SysOrg.dao.findFirst("SELECT * FROM " + SysOrg.TABLE_NAME
								+ " WHERE ID IN (SELECT ORGID FROM " + Cab.TABLE_NAME + " WHERE ID=?) ", cabinetId);
						String status = CaseUtil.getCaseStatusForDep(org, row.getString("id"));
						cabStore.setStatus(status);
						cabStore.setCreateTime(DateKit.toDate(row.getString("createTime")));
						cabStore.setUpdateTime(DateKit.toDate(row.getString("updateTime")));
						cabStore.update();

						Store store = new Store();
						store.setId(cabStore.getId());
						store.setStatus(status);
						CaseUtil.getStoreMapValue(cabinetId, org != null ? org.getCODE() : "", store, cabStore);
						stores.add(store);
						sb.append("'").append(cabStore.getId()).append("'").append(",");

						if (StrKit.equals("53010305", org.getCODE())) {
							Record casepl = Db.use("plga")
									.findFirst("select * from [CASE] t where t.SNO_ = '" + store.getId() + "' ");
							if (casepl != null) {

								CabStoreUser cabStoreUser = CabStoreUser.dao.findFirst(
										"select * from " + CabStoreUser.TABLE_NAME
												+ " where cabId=? and storeId=? and userId=? ",
										cabinetId, store.getId(), casepl.getStr("SID"));
								if (null == cabStoreUser) {
									cabStoreUser = new CabStoreUser();
									cabStoreUser.setId(UuidUtil.getUUID());
									cabStoreUser.setCabId(cabinetId);
									cabStoreUser.setStoreId(store.getId());
									cabStoreUser.setUserId(casepl.getStr("SID"));
									cabStoreUser.setSrc("1");
									cabStoreUser.save();
								}
							}
						}
					}
				}
				if (!StrKit.isBlank(sb.toString())) {
					Db.delete("delete from " + CabStore.TABLE_NAME + " where cabId=? and  id not in ("
							+ (sb.substring(0, sb.length() - 1)) + ") ", cabinetId);
				}
				this.renderSuccess("存储信息保存成功！", stores);
			} else {
				Db.delete("delete from " + CabStore.TABLE_NAME + " where cabId=?", cabinetId);
				Db.delete("delete from " + CabStoreBox.TABLE_NAME + " where cabId=?", cabinetId);
				this.renderError("存储信息空！");
			}
		} catch (Exception e) {
			this.renderError("存储信息空！");
		}
	}

	/**
	 * 柜子存储状态
	 */
	@Before(Tx.class)
	public void saveBoxs() {
		String cabinetId = this.getPara("cabinetId");
		String rows = this.getPara("rows");
		if (StrKit.isBlank(rows)) {
			this.renderError("柜子存储状态信息空！");
			return;
		}
		try {
			JSONArray array = JSONArray.fromObject(rows);
			if (array != null && array.size() > 0) {
				StringBuffer sb = new StringBuffer();
				for (Object object : array) {
					JSONObject row = JSONObject.fromObject(object);
					if (row != null) {
						CabStoreBox cabStoreBox = CabStoreBox.dao.findById(row.getString("id"));
						if (cabStoreBox == null) {
							cabStoreBox = new CabStoreBox();
							cabStoreBox.setId(row.getString("id"));
							cabStoreBox.setCabId(cabinetId);
							cabStoreBox.setBoardId(row.getString("boardId"));
							cabStoreBox.setBoxNo(row.getInt("boxNo"));
							cabStoreBox.setModuleId(row.getString("cabinetId"));
							cabStoreBox.setStoreId(row.getString("storeId"));
							cabStoreBox.save();
						}
						sb.append("'").append(cabStoreBox.getId()).append("'").append(",");
					}
				}
				if (!StrKit.isBlank(sb.toString())) {
					Db.delete("delete from " + CabStoreBox.TABLE_NAME + " where cabId=? and  id not in ("
							+ (sb.substring(0, sb.length() - 1)) + ") ", cabinetId);
				}
				this.renderSuccess("柜子存储状态保存成功！");
			} else {
				this.renderError("柜子存储状态信息空！");
			}
		} catch (Exception e) {
			this.renderError("日志信息空！");
		}
	}

	/**
	 * 保存客户端日志
	 */
	@Before(Tx.class)
	public void saveLogs() {
		String rows = this.getPara("rows");
		String cabinetId = this.getPara("cabinetId");
		if (StrKit.isBlank(rows)) {
			this.renderError("日志信息空！");
			return;
		}
		try {
			JSONArray array = JSONArray.fromObject(rows);
			for (Object object : array) {
				JSONObject row = JSONObject.fromObject(object);
				if (row != null) {
					CabStoreLog cabStoreLog = CabStoreLog.dao.findById(row.getString("id"));
					if(cabStoreLog==null) {
						cabStoreLog = new CabStoreLog();
					}
					cabStoreLog.setCabId(cabinetId);
					cabStoreLog.setModuleId(row.getString("cabinetId"));
					cabStoreLog.setStoreId(row.getString("storeId"));
					cabStoreLog.setStatus(row.getString("status"));
					cabStoreLog.setCreateUserId(row.getString("userId"));
					cabStoreLog.setCreateTime(new Date(System.currentTimeMillis()));
					cabStoreLog.setRecordTime(row.getString("createTime"));
					if(StrKit.isBlank(cabStoreLog.getId())) {
						cabStoreLog.setId(row.getString("id"));
						if (!cabStoreLog.save()) {
							throw new Exception("保存日志异常！");
						}
					}else {
						if (!cabStoreLog.update()) {
							throw new Exception("保存日志异常！");
						}
					}
				}
			}
			this.renderSuccess("日志保存成功！");
		} catch (Exception e) {
			this.renderError("日志信息空1！");
		}
	}

	/**
	 * 保存客户端日志
	 */
	@Before(Tx.class)
	public void saveBoxLogs() {
		String rows = this.getPara("rows");
		String cabinetId = this.getPara("cabinetId");
		if (StrKit.isBlank(rows)) {
			this.renderError("日志信息空！");
			return;
		}
		try {
			JSONArray array = JSONArray.fromObject(rows);
			for (Object object : array) {
				JSONObject row = JSONObject.fromObject(object);
				if (row != null) {
					CabStoreBoxLog cabStoreBoxLog = CabStoreBoxLog.dao.findById(row.getString("id"));
					if(cabStoreBoxLog == null) {
						cabStoreBoxLog = new CabStoreBoxLog();
					}
					cabStoreBoxLog.setCabId(cabinetId);
					cabStoreBoxLog.setModuleId(row.getString("cabinetId"));
					cabStoreBoxLog.setStoreId(row.getString("storeId"));
					cabStoreBoxLog.setStatus(row.getString("status"));
					cabStoreBoxLog.setBoardId(row.getString("boardId"));
					cabStoreBoxLog.setLogId(row.getString("logId"));
					cabStoreBoxLog.setBoxNo(row.getInt("boxNo"));
					cabStoreBoxLog.setCreateTime(row.getString("createTime"));
					
					if(StrKit.isBlank(cabStoreBoxLog.getId())) {
						cabStoreBoxLog.setId(row.getString("id"));
						if (!cabStoreBoxLog.save()) {
							throw new Exception("保存日志异常！");
						}
					}else {
						if (!cabStoreBoxLog.update()) {
							throw new Exception("保存日志异常！");
						}
					}
				}
			}
			this.renderSuccess("日志保存成功！");
		} catch (Exception e) {
			this.renderError("日志信息空！");
		}
	}

	public void getStoreById() {
		String cabinetId = this.getPara("cabinetId");
		String storeId = this.getPara("storeId");

		SysOrg org = SysOrg.dao.findFirst("SELECT * FROM " + SysOrg.TABLE_NAME + " WHERE ID IN (SELECT ORGID FROM "
				+ Cab.TABLE_NAME + " WHERE ID=?) ", cabinetId);
		String status = CaseUtil.getCaseStatusForDep(org, storeId);

		Store store = new Store();
		store.setId(storeId);
		store.setStatus(status);
		CaseUtil.getStoreMapValue(cabinetId, org != null ? org.getCODE() : "", store);
		this.renderSuccess("成功。", store);
	}

}
